package com.simpletour.qa.common.repository;


import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author liuliyuan
 * @date 2017/12/6 9:29
 * @Description: LocalDateTime <==> Long
 * Entity属性为LocalDateTime时会自动生效
 */
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Long> {

    @Override
    public Long convertToDatabaseColumn(LocalDateTime attribute) {
        return attribute == null ? 0L : attribute.atZone(ZoneOffset.ofHours(0)).toEpochSecond();
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Long dbData) {
        return dbData != null && dbData != 0L ? Dates.fromEpochSecond(dbData) : null;
    }
}
